package com.imooc.ecommerce.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.ecommerce.account.BalanceInfo;
import com.imooc.ecommerce.entity.EcommerceBalance;
import com.imooc.ecommerce.filter.AccessContext;
import com.imooc.ecommerce.mapper.EcommerceBalanceMapper;
import com.imooc.ecommerce.service.IBalanceService;
import com.imooc.ecommerce.vo.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用于余额相关服务接口实现
 * @Author: zhangshao
 * @Since: 2023/11/28 14:35
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BalanceServiceImpl extends ServiceImpl<EcommerceBalanceMapper, EcommerceBalance>
		implements IBalanceService {
	@Override
	public BalanceInfo getCurrentUserBalanceInfo() {
		LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();
		BalanceInfo balanceInfo = new BalanceInfo(loginUserInfo.getId(), 0L);
		EcommerceBalance ecommerceBalance = new LambdaQueryChainWrapper<>(this.getBaseMapper())
				.eq(EcommerceBalance::getUserId, loginUserInfo.getId()).one();
		if (null != ecommerceBalance) {
			balanceInfo.setBalance(ecommerceBalance.getBalance());
		} else {
			// 如果还没有用户余额记录，创建出来，设定余额为0
			EcommerceBalance newBalance = new EcommerceBalance();
			newBalance.setUserId(loginUserInfo.getId());
			newBalance.setBalance(0L);
			this.save(newBalance);
			log.info("init user balance record :[{}]", newBalance.getId());
		}
		return balanceInfo;
	}

	@Override
	public BalanceInfo deductBalance(BalanceInfo balanceInfo) {

		LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();

		//扣减用户余额的基本原则：扣减额 <= 当前用户余额
		EcommerceBalance ecommerceBalance = new LambdaQueryChainWrapper<>(this.getBaseMapper())
				.eq(EcommerceBalance::getUserId, loginUserInfo.getId()).one();
		if (null == ecommerceBalance || ecommerceBalance.getBalance() - balanceInfo.getBalance() < 0) {
			throw new RuntimeException("user balance is not enough!");
		}
		Long sourceBalance = ecommerceBalance.getBalance();
		ecommerceBalance.setBalance(ecommerceBalance.getBalance() - balanceInfo.getBalance());
		this.updateById(ecommerceBalance);
		log.info("deduct balance：[{}],[{}],[{}]", ecommerceBalance.getId(), sourceBalance, balanceInfo.getBalance());
		return new BalanceInfo(ecommerceBalance.getUserId(), ecommerceBalance.getBalance()
		);
	}
}
